# -*- coding: utf-8 -*-
#
#    Copyright (C) 2012 Gonzalo Bonigo <gonzalobonigo@gmail.com>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see http://www.gnu.org/licenses/
#


"""Este archivo contiene la definicion del metodo twin_plant_method()."""


__all__ = [
    "twin_plant_method"
]


import os.path
import time
import sys
import os

from lts import utils
import lts


def twin_plant_method(parsed_args):
    # Pongo los argumentos en variables para facilitar su acceso.
    system = parsed_args["system"]
    fault_set = parsed_args["fault_set"]
    take_time = parsed_args["time"]
    verbose = parsed_args["verbose"]
    # Para la salida por pantalla.
    first_iter = True
    # Analizo la diagnosticabilidad para cada falla.
    for fault in fault_set:
        if first_iter:
            first_iter = False
        else:
            print "\n--------------------------------------------------"
        print "\n-> Checkign diagnosability for fault", fault
        if verbose:
            print ""
        # Armo un nombre para mostrar lo que estoy sincronizando.
        sync_sep = '||'
        sync_name_list = [x.name.replace('.aut','') for x in system]
        sync_name = sync_sep.join(sync_name_list)
        # Compongo y analizo.
        c = None # Almacena la composicion.
        if verbose:
            print "Synchronizing:", sync_name
        if take_time:
            t1 = time.time()
        for i in range(0,len(system)):
            if i == 0:
                c = system[i]
            else:
                c = c.sync(system[i], None, None, False, False)
        # Analizo la diagnosticabilidad de la composicion.
        if verbose:
            print "Checking diagnosability for", c.name.replace('.aut', '')
            print "Building twin-plant..."
        c.get_twinplant()
        if verbose:
            print "Analyzing..."
        dc = c.is_diagnosable(set([fault]))
        if take_time:
            t2 = time.time()
        if dc['is_diag']:
            print "\n=> The system is diagnosable for fault "+fault+"\n"
        else:
            print "\n=> The system is non-diagnosable for fault "+fault+"\n"
        if take_time:
            print "Time:", utils.str_time(t2 - t1)
        if verbose:
            print ""
        # Guardo la composicion en un archivo.
        lts.LTS.to_file(c)
